"""
SQLAlchemy 数据库模型

定义文件上传相关的表结构
"""

from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey, Enum as SQLEnum
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
import enum
import sys
from pathlib import Path

# 处理导入路径
if __name__ == "__main__" or "." not in __name__:
    sys.path.insert(0, str(Path(__file__).parent.parent.parent))
    from stage2_advanced.chapter03_file_upload.database import Base
else:
    from .database import Base


# ========== 枚举类型 ==========

class FileType(str, enum.Enum):
    """文件类型枚举"""
    IMAGE = "image"
    DOCUMENT = "document"
    VIDEO = "video"
    AUDIO = "audio"
    OTHER = "other"


class FileStatus(str, enum.Enum):
    """文件状态枚举"""
    UPLOADING = "uploading"
    COMPLETED = "completed"
    PROCESSING = "processing"
    FAILED = "failed"
    DELETED = "deleted"


# ========== 数据库模型 ==========

class UploadedFile(Base):
    """
    上传文件模型
    
    记录所有上传的文件信息
    """
    
    __tablename__ = "uploaded_files"
    
    # 主键
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    
    # 文件信息
    filename = Column(String(255), nullable=False, comment="原始文件名")
    stored_filename = Column(String(255), nullable=False, unique=True, comment="存储文件名")
    file_path = Column(String(500), nullable=False, comment="文件存储路径")
    file_type = Column(SQLEnum(FileType), nullable=False, comment="文件类型")
    file_size = Column(Integer, nullable=False, comment="文件大小（字节）")
    mime_type = Column(String(100), nullable=True, comment="MIME 类型")
    file_hash = Column(String(64), nullable=True, comment="文件哈希值（SHA256）")
    
    # 图片专用字段
    width = Column(Integer, nullable=True, comment="图片宽度")
    height = Column(Integer, nullable=True, comment="图片高度")
    
    # 状态
    status = Column(SQLEnum(FileStatus), default=FileStatus.COMPLETED, comment="文件状态")
    
    # 上传者信息
    uploader_id = Column(Integer, nullable=True, comment="上传者 ID")
    uploader_ip = Column(String(45), nullable=True, comment="上传者 IP")
    
    # 元数据
    description = Column(String(500), nullable=True, comment="文件描述")
    tags = Column(String(500), nullable=True, comment="标签（逗号分隔）")
    
    # 访问控制
    is_public = Column(Boolean, default=False, comment="是否公开")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="上传时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 关系
    thumbnails = relationship("FileThumbnail", back_populates="original_file", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<UploadedFile(id={self.id}, filename='{self.filename}', type='{self.file_type}')>"


class FileThumbnail(Base):
    """
    文件缩略图模型
    
    记录图片文件的缩略图
    """
    
    __tablename__ = "file_thumbnails"
    
    # 主键
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    
    # 关联原文件
    file_id = Column(Integer, ForeignKey("uploaded_files.id", ondelete="CASCADE"), nullable=False)
    
    # 缩略图信息
    size_name = Column(String(50), nullable=False, comment="尺寸名称（small/medium/large）")
    filename = Column(String(255), nullable=False, comment="缩略图文件名")
    file_path = Column(String(500), nullable=False, comment="缩略图路径")
    width = Column(Integer, nullable=False, comment="宽度")
    height = Column(Integer, nullable=False, comment="高度")
    file_size = Column(Integer, nullable=False, comment="文件大小")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # 关系
    original_file = relationship("UploadedFile", back_populates="thumbnails")
    
    def __repr__(self):
        return f"<FileThumbnail(id={self.id}, file_id={self.file_id}, size='{self.size_name}')>"

